// LoginPage.js
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import '../Css/Login.css';

const Login = ({ onLogin }) => {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const [loginMessage, setLoginMessage] = useState('');
  const navigate = useNavigate();

  const onSubmit = data => {
    axios.post('http://127.0.0.1:5000/login', data)
      .then(response => {
        console.log(response.data);
        setLoginMessage('登录成功！');
        setTimeout(() => {
          console.log('User logged in');
          onLogin(); // 确保在登录成功后调用 onLogin 函数
          navigate('/'); // 登录成功后导航到主页面
        }, 2000);
      })
      .catch(error => {
        console.error(error);
      });
  };

  return (
    <div className="login-container">
      <div className="login-content">
        <h2>用户登录</h2>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="form-group">
            <label>用户名</label>
            <input {...register('username', { required: true })} className="form-control" />
            {errors.username && <span className="error-message">用户名不能为空</span>}
          </div>
          <div className="form-group">
            <label>密码</label>
            <input {...register('password', { required: true })} type="password" className="form-control" />
            {errors.password && <span className="error-message">密码不能为空</span>}
          </div>
          <button type="submit" className="btn btn-primary">登录</button>
          <button className="btn btn-secondary" onClick={() => navigate('/register')}>注册</button>
        </form>
        {loginMessage && <div className="login-message">{loginMessage}</div>}
      </div>
    </div>
  );
};

export default Login;
